<template>
  <div class="user-management">
    <div class="header-actions">
      <h2>用户管理</h2>
      <button @click="showAddDialog = true" class="add-btn">
        添加用户
      </button>
    </div>

    <div class="search-bar">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索用户名..."
        @input="handleSearch"
      >
      <select v-model="roleFilter" @change="handleSearch">
        <option value="">全部角色</option>
        <option value="admin">管理员</option>
        <option value="user">普通用户</option>
      </select>
    </div>

    <div class="users-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>角色</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>
              <span :class="['role-badge', user.role]">
                {{ user.role === 'admin' ? '管理员' : '普通用户' }}
              </span>
            </td>
            <td>{{ formatDate(user.created_at) }}</td>
            <td>
              <button @click="editUser(user)" class="edit-btn">编辑</button>
              <button @click="deleteUser(user.id)" class="delete-btn">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>{{ showEditDialog ? '编辑用户' : '添加用户' }}</h3>
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="currentUser.username" required>
          </div>
          <div class="form-group">
            <label>密码</label>
            <input 
              type="password" 
              v-model="currentUser.password" 
              :required="!showEditDialog"
            >
            <small v-if="showEditDialog">留空表示不修改密码</small>
          </div>
          <div class="form-group">
            <label>角色</label>
            <select v-model="currentUser.role" required>
              <option value="user">普通用户</option>
              <option value="admin">管理员</option>
            </select>
          </div>
          <div class="dialog-actions">
            <button type="submit" class="confirm-btn">
              {{ showEditDialog ? '保存' : '添加' }}
            </button>
            <button type="button" @click="closeDialog" class="cancel-btn">
              取消
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../../api/config';
import axios from 'axios';

export default {
  name: 'UserManagement',
  data() {
    return {
      users: [],
      searchQuery: '',
      roleFilter: '',
      showAddDialog: false,
      showEditDialog: false,
      currentUser: {
        username: '',
        password: '',
        role: 'user'
      }
    };
  },
  computed: {
    filteredUsers() {
      return this.users.filter(user => {
        const matchesSearch = 
          user.username.toLowerCase().includes(this.searchQuery.toLowerCase());
        const matchesRole = !this.roleFilter || user.role === this.roleFilter;
        return matchesSearch && matchesRole;
      });
    }
  },
  methods: {
    async fetchUsers() {
      try {
        console.log('开始获取用户列表...');
        const response = await axios.get(API_ENDPOINTS.USER.GET_ALL);
        console.log('用户列表获取成功:', response.data);
        console.log('用户列表数据结构:', JSON.stringify(response.data, null, 2));
        this.users = response.data;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        console.error('错误详情:', error.response ? error.response.data : error.message);
        alert('获取用户列表失败');
      }
    },
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    editUser(user) {
      this.currentUser = { ...user, password: '' };
      this.showEditDialog = true;
    },
    async deleteUser(userId) {
      if (!confirm('确定要删除这个用户吗？')) return;
      
      try {
        await axios.delete(API_ENDPOINTS.USER.DELETE(userId));
        this.users = this.users.filter(user => user.id !== userId);
        alert('删除成功');
      } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败');
      }
    },
    async handleSubmit() {
      try {
        const userData = { ...this.currentUser };
        if (this.showEditDialog && !userData.password) {
          delete userData.password;
        }

        if (this.showEditDialog) {
          await axios.put(API_ENDPOINTS.USER.UPDATE(userData.id), userData);
          const index = this.users.findIndex(u => u.id === userData.id);
          this.users[index] = { ...userData };
        } else {
          const response = await axios.post(API_ENDPOINTS.USER.CREATE, userData);
          const newUser = {
            id: response.data.user.id,
            username: response.data.user.username,
            role: response.data.user.role,
            created_at: new Date().toISOString()
          };
          this.users.push(newUser);
        }
        
        this.closeDialog();
        alert(this.showEditDialog ? '更新成功' : '添加成功');
      } catch (error) {
        console.error('操作失败:', error);
        alert('操作失败');
      }
    },
    closeDialog() {
      this.showAddDialog = false;
      this.showEditDialog = false;
      this.currentUser = {
        username: '',
        password: '',
        role: 'user'
      };
    }
  },
  created() {
    this.fetchUsers();
  }
};
</script>

<style scoped>
.user-management {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-bar input,
.search-bar select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-bar input {
  flex: 1;
}

.users-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.role-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
}

.role-badge.admin {
  background-color: #e74c3c;
  color: white;
}

.role-badge.user {
  background-color: #3498db;
  color: white;
}

.edit-btn,
.delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
}

.edit-btn {
  background-color: #3498db;
  color: white;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group small {
  display: block;
  margin-top: 4px;
  color: #666;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background-color: #42b983;
  color: white;
}

.cancel-btn {
  background-color: #666;
  color: white;
}
</style>